package com.example.onlineanswer.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.onlineanswer.model.entity.Question;
import com.example.onlineanswer.model.vo.QuestionVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 题目数据访问接口
 */
@Mapper
public interface QuestionMapper extends BaseMapper<Question> {

    /**
     * 根据竞赛ID获取题目列表
     *
     * @param contestId 竞赛ID
     * @return 题目列表
     */
    @Select("SELECT q.* FROM question q " +
           "WHERE q.contest_id = #{contestId} AND q.is_deleted = 0 " + 
           "ORDER BY q.order_num ASC")
    List<Question> getQuestionsByContestId(@Param("contestId") Long contestId);

    /**
     * 分页查询题目列表
     *
     * @param page         分页参数
     * @param contestId    竞赛ID（可选）
     * @param contestTitle 竞赛名称（可选）
     * @param typeId       题目类型ID（可选）
     * @param difficulty   难度（可选）
     * @param status       状态（可选）
     * @param keyword      关键词（可选）
     * @return 题目列表
     */
    IPage<QuestionVO> pageQuestionList(Page<QuestionVO> page, 
                                      @Param("contestId") Long contestId,
                                      @Param("contestTitle") String contestTitle,
                                      @Param("typeId") Integer typeId,
                                      @Param("difficulty") Integer difficulty, 
                                      @Param("status") Integer status,
                                      @Param("keyword") String keyword);

    /**
     * 获取竞赛的题目数量
     *
     * @param contestId 竞赛ID
     * @return 题目数量
     */
    @Select("SELECT COUNT(*) FROM question WHERE contest_id = #{contestId} AND status = 1 AND is_deleted = 0")
    int getQuestionCountByContestId(@Param("contestId") Long contestId);

    /**
     * 根据ID获取题目详情
     *
     * @param id 题目ID
     * @return 题目详情
     */
    @Select("SELECT q.*, t.type_name, c.title as contest_title " +
            "FROM question q " +
            "LEFT JOIN question_type t ON q.type_id = t.id " +
            "LEFT JOIN contest c ON q.contest_id = c.id " +
            "WHERE q.id = #{id} AND q.is_deleted = 0")
    QuestionVO getQuestionDetailById(@Param("id") Long id);

    /**
     * 获取下一题（根据orderNum）
     *
     * @param contestId 竞赛ID
     * @param currentOrderNum 当前题目序号
     * @return 下一题ID
     */
    @Select("SELECT id FROM question " +
            "WHERE contest_id = #{contestId} AND order_num > #{currentOrderNum} AND is_deleted = 0 " +
            "ORDER BY order_num ASC LIMIT 1")
    Long getNextQuestionId(@Param("contestId") Long contestId, @Param("currentOrderNum") Integer currentOrderNum);
} 